<template>
	<view class="container">
		<view class="book_name">
			<text>{{details.name}}</text>
			<view class="book_state">{{roomStatusText(details.room_status)}}</view>
		</view>

		<view class="book_box">
			<view class="book_date" v-if="day_week.length">
				<view class="day_week" :class="{active:index==check_index}" v-for="(item,index) in day_week"
					:key="index" @tap="check_day(index,item)">
					<text>{{item.date}}</text>
					<text>{{index==0?"今天":item.week}}</text>
				</view>
			</view>

			<view class="select_time">
				<view class="start_time">
					<text>開始時間</text>
					<!-- <picker mode="time" :start="startTime" @change="selectStartTime" style="flex: 1;"> -->
					<view class="inp" @tap="showStart = true">
						<!-- <input :value="startValue" type="text" placeholder="請選擇開始時間"
							placeholder-style="font-size:24rpx"> -->
						<view class="">{{startValue}}</view>
						<image src="/static/images/xiangxiajiantou.png" mode=""></image>
					</view>
					<u-datetime-picker confirmText="確認" v-model="startTimeValue" @confirm="confirmStart"
						:closeOnClickOverlay="true" @close="showStart=false" @cancel="showStart=false" :show="showStart"
						mode="time"></u-datetime-picker>
					<!-- </picker> -->
				</view>
				<!-- <view class="end_time">
					<text>結束時間</text>
					<picker mode="time" :start="startTime" @change="selectEndTime" style="flex: 1;">
						<view class="inp">
							<input :value="endValue" type="text" placeholder="請選擇結束時間"
								placeholder-style="font-size:24rpx">
						</view>
					</picker>
				</view> -->
				<!-- <view class="end_time">
					<text>使用時長</text>
					<view class="inp" @tap="showSelectUseDuration" :class="{active:!showEndTime}">
						<input :value="useDuration" :disabled="!showEndTime" type="text" placeholder="請選擇使用時長"
							placeholder-style="font-size:20rpx;color:#999;">

					</view>
					<u-picker @confirm='confirmUseDuration' @close='showUseDuration=false'
						@cancel='showUseDuration=false' :closeOnClickOverlay="true" :show="showUseDuration"
						:columns="columns"></u-picker>
				</view> -->
			</view>

			<view class="can_book_time">
				<text>已預訂時段</text>
				<text>可預訂時段</text>
			</view>

			<view class="period_time">
				<view class="book_day">{{bookDay}}</view>
				<!-- <view class="book_state_time box">
					<view style="display: flex;">
						<view v-for="(Numitem,index) in num_time_stamp" :key="index"
							:style="{width:100/num_time.length + '%' }"
							style="border: 1rpx solid #707070;height: 30rpx;">
							<view class="" v-for="(deepItem,dindex) in changeTime(details.times)" :key="dindex">
								<view v-if="Numitem>=deepItem.start && Numitem<=deepItem.end" class="deep"></view>
							</view>
						</view>
					</view>
					<view class="item">
						<view :style="{width:100/num_time.length + '%' }" v-for="(item,index) in num_time" :key="index">
							<text>{{cut(item,'hour')}}</text>
						</view>
					</view>
				</view> -->
				<view class="book_state_time box">
					<view style="display: flex;">
						<view class="bs" style="height: 30rpx;" v-for="(timeBarItem,timebarIndex) in timeBar"
							:key="timebarIndex" :style="{width:100/timeBar.length + '%' }">
							<view class="bs_deep" v-for="(orderTimeItem,orderIndex) in orderTimelot(details.times)"
								:key="orderIndex">
								<view class="deep" :style="{width:setWidth(timeBarItem,orderTimeItem) + '%'}"
									v-if="timeBarItem>=orderTimeItem.start && timeBarItem<=orderTimeItem.end"></view>
							</view>
						</view>
					</view>
					<view class="item">
						<view :style="{width:100/timeBarText.length + '%' }" v-for="(item,index) in timeBarText"
							:key="index">
							<text>{{item==0?'次日':item}}</text>
						</view>
					</view>
				</view>
			</view>

		</view>

		<view class="place_order">
			<view class="title">下單須知：</view>
			<view class="" v-if="!notice">
				<view class="prompt">1.訂單保留15分鐘，15分鐘自動確認到店</view>
				<view class="prompt">2.訂單最多可提前60分鐘確認到店(前面沒其他客人)</view>
				<view class="prompt">3.如需取消，請聯繫客服人員</view>
			</view>
			<view class="" v-else>
				<view class="prompt" v-for="(item,index) in notice" :key="index">{{item}}</view>
			</view>
		</view>

		<view class="btn">
			<view class="book_btn" @tap="book">預訂</view>
		</view>

	</view>
</template>

<script>
	import dayjs from "dayjs"
	import {
		getStoreInfo
	} from '@/api/me.js'
	import {
		reservationOrder
	} from '@/api/index.js'

	import store from '@/store/index.js'

	import {
		getOrderNotice
	} from '@/api/order.js'

	export default {
		data() {
			return {
				day_week: [],
				check_index: 0,
				num_time: [],
				num_time_stamp: [],
				colorDeep: [],
				startTime: "",
				startValue: "",
				endValue: "",
				bookDay: "",
				// check_package: 0,
				details: '',
				storeInfo: '',
				storeConfig: null,
				showUseDuration: false,
				columns: [],
				showEndTime: true,
				useDuration: '',
				showStart: false,
				startTimeValue: '',
				ticketRollId: '', // 電子票券id
				ticketRollInfo: '', // 電子票券詳情

				// 时间展示条
				timeBar: [], // 存放当前时间之后的24小时
				timeBarText: [], // 存放时间文本
				notice: null,
			};
		},
		onLoad(option) {

			// this.ticketRollId = option.id
			// this.ticketRollInfo = JSON.parse(option.ticketRollInfo)
			this.ticketRollInfo = store.state.ticketInfo
			this.ticketRollId = this.ticketRollInfo.id
			console.log(this.ticketRollInfo, '電子票券詳情')

			this.getTimeandWeek()
			this.startTime = dayjs().hour() + ":" + dayjs().minute()
			this.bookDay = dayjs().year() + "-" + this.addMarh(dayjs().month() + 1) + "-" + this.addMarh(dayjs().date())

			// this.details = JSON.parse(option.details)
			this.details = store.state.roomInfo
			// console.log(this.details, '詳情')

			getStoreInfo({
				store_id: this.details.store_id
			}).then(res => {
				this.storeInfo = res.data
				this.storeConfig = res.data.store_config
				// console.log(res.data, '店鋪詳情')
				this.reservation_time(this.storeInfo.open, this.storeInfo.close)
				this.setupDuration(this.store_config)
				this.getOrderNoticeFn(this.storeInfo.id)
			})

			this.setStartModel()
			this.computedEndTime(this.startValue, this.ticketRollInfo.use_hours)

			this.setTimeBar()
		},
		methods: {
			getOrderNoticeFn(store_id) {
				getOrderNotice({
					store_id
				}).then(res => {
					// console.log(res, '下單須知')
					if (res.data) {
						const se = /[；。\n]/
						this.notice = res.data.split(se)
						// console.log(this.notice, '下單須知')
					}
				})
			},
			check_day(index, key) {
				this.check_index = index
				this.bookDay = `${key.year}-${key.date}`
			},
			getTimeandWeek() {
				//获取当前时间
				var now = new Date();
				//往后几天就循环几次
				for (let i = 0; i < 6; i++) {
					//24 * 3600 * 1000 就是计算一天的时间  
					var date = new Date(now.getTime() + i * 24 * 3600 * 1000);
					var year = date.getFullYear();
					var month = date.getMonth() + 1;

					var day = date.getDate();
					var dt2 = new Date(now.getTime() + i * 24 * 3600 * 1000);
					var weekDay = ['周天', '周一', '周二', '周三', '周四', '周五', '周六'];
					//把七天的时间和星期添加到数组中
					this.day_week.push({
						// date: year + '-' + this.addMarh(month) + '-' + this.addMarh(day),
						date: this.addMarh(month) + '-' + this.addMarh(day),
						week: weekDay[dt2.getDay()],
						checked: false,
						year
					});
				}
			},
			addMarh(date) {
				return date = date < 10 ? "0" + date : date
			},
			selectStartTime(e) {
				// console.log(e,"選擇時間")
				this.startValue = e.detail.value
			},
			selectEndTime(e) {
				this.endValue = e.detail.value
			},
			roomStatusText(status) {
				switch (status) {
					case 0:
						return '空閒';
					case 1:
						return '預訂';
					case 2:
						return '待打掃';
					case 3:
						return '打掃中';
					case 4:
						return '故障';
				}
			},
			// 設置開店總時長
			reservation_time(open, close) {
				// 開店時間
				let start = this.timeStamp(open, 'hour')
				// 關店時間
				let end = this.timeStamp(close, 'hour')
				if (end <= start) {
					end = end + 24 * 60 * 60 * 1000
				}

				if (this.storeConfig) {
					// 根據店鋪配置的時間表間隔設置長度
					// 時間表間隔的時間戳
					let stamp = this.timeStamp(this.storeConfig.schedule_interval, 'hour')
					// 終止預約時間（即關店前幾小時不允許預約訂單）
					let orderEnd = this.timeStamp(this.storeConfig.order_end_time, 'hour')

					stamp = stamp ? stamp : 60 * 60 * 1000

					let arr = []
					for (var i = start; i <= end - orderEnd; i += stamp) {
						arr.push(i)
					}
					this.num_time_stamp = [...arr]

					let arrTime = []
					arr.forEach(item => {
						let h = this.montage(this.stampTime(item, 'hour'))
						let m = this.montage(this.stampTime(item, 'minute'))
						arrTime.push(h + ':' + m)
					})
					// console.log(arrTime, 'arrTime')
					this.num_time = [...arrTime]
				} else {
					let arr = []
					for (var i = start; i <= end; i += 60 * 60 * 1000) {
						arr.push(i)
					}
					this.num_time_stamp = [...arr]
					let arrTime = []
					arr.forEach(item => {
						let h = this.montage(this.stampTime(item, 'hour'))
						let m = this.montage(this.stampTime(item, 'minute'))
						arrTime.push(h + ':' + m)
					})
					// console.log(arrTime, 'arrTime')
					this.num_time = [...arrTime]
				}

			},
			// 將時間轉換成時間戳
			timeStamp(str, type) {
				if (!str) return 0
				if (type == 'hour') {
					return Number(str.split(':')[0]) * 60 * 60 * 1000 + Number(str.split(':')[1]) * 60 * 1000
				}
			},
			// 將時間戳轉換成時間
			stampTime(num, type) {
				if (type === 'hour') {
					return Math.floor(num / 60 / 60 / 1000)
				} else if (type == 'minute') {
					return Math.floor((num % (60 * 60 * 1000)) / (60 * 1000))
				}
			},
			montage(num) {
				return num >= 10 ? num : '0' + num
			},
			cut(time, type) {
				if (time.indexOf(':') !== -1) {
					if (type == 'hour') {
						return time.split(':')[0]
					} else if (type == 'minute') {
						return time.split(':')[1]
					}
				} else {
					if (type == 'hour') {
						return time
					} else if (type == 'minute') {
						return ''
					}
				}
			},
			changeTime(times) {
				let arr = []
				times.forEach(item => {
					let startH = new Date(item.start * 1000).getHours() * 60 * 60 * 1000
					let startM = new Date(item.start * 1000).getMinutes() * 60 * 1000
					let endH = new Date(item.end * 1000).getHours() * 60 * 60 * 1000
					let endM = new Date(item.end * 1000).getMinutes() * 60 * 1000
					arr.push({
						start: startH + startM,
						end: endH + endM
					})
				})
				return arr
			},
			confirmUseDuration(e) {
				this.useDuration = e.value[0]
				this.showUseDuration = false
			},
			showSelectUseDuration() {
				if (this.showEndTime) {
					this.showUseDuration = true
				}
			},
			confirmStart(e) {
				// console.log(e)
				this.startValue = e.value
				this.showStart = false
				this.computedEndTime(e.value, this.ticketRollInfo.use_hours)
			},
			setStartModel() {
				let h = new Date().getHours()
				let m = new Date().getMinutes()
				let time = h * 60 * 60 * 1000 + (m + 5) * 60 * 1000
				this.startTimeValue = Math.floor(time / 60 / 60 / 1000) + ":" + Math.floor((time % (60 * 60 * 1000)) / 60 /
					1000)
				this.startValue = this.startTimeValue
			},
			setupDuration(config) {
				// console.log(config, '配置')
				if (config) {
					// 默認預約時長  --- 時間戳
					let defaultBookDuration = Number(config.order_duration * 60 * 60 * 1000)
					// 最小計費時長
					// let minChargingDuration = Number(config.charging_min_time.split(':')[1] * 60 * 1000)
					let minChargingDuration = Number(config.charging_min_time) * 60 * 1000
					// console.log(defaultBookDuration, minChargingDuration)

					let arr = []
					// if (minChargingDuration <= defaultBookDuration) {
					for (var i = minChargingDuration; i <= 8 * 60 * 60 * 1000; i += minChargingDuration) {
						arr.push(i)
					}
					// } else {}

					let arr1 = []
					arr.forEach(item => {
						let h = Math.floor(item / 60 / 60 / 1000)
						let m = Math.floor((item % (60 * 60 * 1000) / 60 / 1000))
						if (h > 0) {
							if (m > 0) {
								arr1.push(h + '小時' + m + '分鐘')
							} else {
								arr1.push(h + '小時')
							}
						} else {
							arr1.push(m + '分鐘')
						}
					})
					// console.log(arr1)
					this.columns = [
						[...arr1, '全天']
					]

				} else {
					this.columns = [
						['1小時', '2小時', '3小時', '4小時', '5小時', '6小時', '7小時', '8小時', '全天']
					]
				}
			},
			computedEndTime(start, duration) {
				// console.log(this.bookDay,start,duration,'111111111')
				let startTime = this.timeStamp(start, 'hour')
				let durationTime = this.timeStamp(duration, 'hour')
				let endTime = startTime + durationTime
				console.log(endTime, '结束时间', startTime, durationTime)

				this.endValue = this.montage(this.stampTime(endTime, 'hour')) + ":" + this.montage(this.stampTime(endTime,
					'minute'))
				// console.log(this.endValue,'11111')


			},
			book() {
				reservationOrder({
					room_id: this.details.id,
					pay_type: 8,
					money: 0,
					date: this.bookDay,
					card_id: this.ticketRollId,
					timeslot: this.startValue + ',' + this.endValue
				}).then(res => {
					if (res.code == 1) {
						uni.showToast({
							title: res.msg,
							icon: 'success',
							duration: 2000
						})
						setTimeout(() => {
							uni.reLaunch({
								url: `/pages/order_details/order_details?id=${res.data.id}`
							})
						}, 2000)
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none",
							duration: 2000
						})
					}

				})
			},
			// 时间条
			setTimeBar() {
				// 获取当前时间的时间戳
				let now = new Date().getTime()
				let end = now + 3600000 * 24
				for (var i = now; i <= end; i += 1800000) {
					this.timeBar.push(i)
				}
				for (var j = now; j <= end; j += 3600000) {
					this.timeBarText.push(this.setTimeHours(j))
				}
			},
			setTimeHours(num) {
				return new Date(num).getHours()
			},
			orderTimelot(arr) {
				if (!arr.length) return []
				let a = []
				arr.forEach(item => {
					a.push({
						start: item.start * 1000,
						end: item.end * 1000
					})
				})
				return a
			},
			setWidth(time, item) {
				return item.end / time * 100
				// console.log(item.end / time)
				// return 100
			},
		},
	}
</script>

<style lang="less">
	.container {
		background-color: #F3F5F9;
		height: calc(100vh - 90rpx);
		padding: 30rpx;
		box-sizing: border-box;

		.book_name {
			display: flex;
			align-items: center;

			text {
				font-size: 30rpx;
				font-weight: bold;
			}

			.book_state {
				width: 117rpx;
				height: 46rpx;
				background: #39B19D;
				border-radius: 16rpx 16rpx 16rpx 16rpx;
				opacity: 1;
				margin-left: 41rpx;
				text-align: center;
				line-height: 46rpx;
				color: #FFF;
				font-size: 24rpx;
			}
		}

		.book_box {
			// height: 1162rpx;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			opacity: 1;
			margin-top: 16rpx;
			padding-top: 16rpx;
			padding-bottom: 16rpx;
			box-sizing: border-box;

			.book_date {
				padding: 0 45rpx;
				display: flex;
				justify-content: space-between;

				.day_week {
					width: 89rpx;
					height: 81rpx;
					background: #fff;
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					opacity: 1;
					border: 1rpx solid #707070;
					font-size: 24rpx;
					padding: 9rpx;
					box-sizing: border-box;
					text-align: center;
				}

				.active {
					background: #F8FDFB;
					border-color: #39B19D;
				}
			}

			.select_time {
				margin: 31rpx 0 72rpx;

				.start_time,
				.end_time {
					display: flex;
					align-items: center;
					padding: 0 37rpx 0 13rpx;
					box-sizing: border-box;
					margin-bottom: 19rpx;

					text {
						font-size: 26rpx;
					}

					.inp {
						width: 514rpx;
						// flex: 1;
						height: 57rpx;
						background: #F3F5F9;
						border-radius: 16rpx 16rpx 16rpx 16rpx;
						opacity: 1;
						border: 1rpx solid #707070;
						padding: 0 16rpx;
						box-sizing: border-box;
						margin-left: 30rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;

						image {
							width: 31rpx;
							height: 26rpx;
						}
					}

				}
			}

			.can_book_time {
				display: flex;
				justify-content: space-around;
				margin-bottom: 29rpx;

				text {
					font-size: 24rpx;
					// margin-left: 7rpx;
					display: flex;
					align-items: center;

					&::before {
						content: "";
						display: inline-block;
						width: 30rpx;
						height: 30rpx;
						background: #39B19D;
						border-radius: 0rpx 0rpx 0rpx 0rpx;
						opacity: 1;
						border: 1rpx solid #707070;
						margin-right: 7rpx;
					}

					&:last-child::before {
						background-color: #fff;
					}
				}
			}

			.period_time {
				padding: 0 11rpx;

				.book_day {
					font-size: 17rpx;
					margin-bottom: 15rpx;
				}

				.deep {
					background: #39B19D;
					height: 30rpx;
				}

				.item {
					display: flex;
					font-size: 17rpx;
					text-align: center;

					view {
						display: flex;
						justify-content: center;
						flex-direction: column;
					}
				}

				.book_state_time {
					padding: 0 11rpx;

					.bs {
						border: 1rpx solid #707070;
						border-right: none;
						position: relative;

						&:last-child {
							border-right: 1rpx solid #707070;
						}

						&:nth-child(2n) {
							border-left: none;

							&::before {
								content: '';
								width: 1rpx;
								height: 50%;
								display: block;
								position: absolute;
								background-color: #FA533D;
								left: 0%;
								bottom: 0%;
								z-index: 2;
							}
						}

						.bs_deep {
							position: relative;
						}

						.deep {
							background: #39B19D;
							height: 30rpx;
							// width: 30rpx;
							width: 100%;
							position: absolute;
							z-index: 1;
						}
					}

					.item {
						display: flex;
						font-size: 17rpx;
						// text-align: center;

						view {
							display: flex;
							justify-content: center;
							flex-direction: column;
						}
					}
				}
			}
		}

		.place_order {
			margin: 23rpx 0rpx 47rpx;

			.title {
				font-size: 30rpx;
				color: #000;
				font-weight: bold;
			}

			.prompt {
				font-size: 28rpx;
				color: #000;
				margin-top: 10rpx;
			}
		}

		.btn {
			display: flex;
			justify-content: flex-end;
		}

		.book_btn {
			width: 143rpx;
			height: 51rpx;
			background: #39B19D;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			opacity: 1;
			border: 1rpx solid #39B19D;
			color: #fff;
			font-size: 36rpx;
			text-align: center;
			line-height: 51rpx;
		}
	}
</style>